package apple.eclipse.views;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.part.ViewPart;

import apple.ui.swt.Keyboard;
import apple.ui.swt.Monitor;

public class MonitorView extends ViewPart {
   public static final String ID = "javapple2.monitor";

   private Monitor monitor;

   private Keyboard keyboard;

   public void createPartControl(Composite parent) {
      monitor = new Monitor(parent);
      keyboard = new Keyboard();
      monitor.addKeyListener(keyboard);
      getSite().setSelectionProvider(new MonitorSelectionProvider());
   }

   public void setFocus() {
      monitor.setFocus();
   }

   public Monitor getMonitor() {
      return monitor;
   }

   public Keyboard getKeyboard() {
      return keyboard;
   }

   private class MonitorSelectionProvider implements ISelectionProvider {
      List<ISelectionChangedListener> listeners = new ArrayList<ISelectionChangedListener>();

      public void addSelectionChangedListener(ISelectionChangedListener listener) {
         if (!listeners.contains(listener)) {
            listeners.add(listener);
         }
      }

      public void removeSelectionChangedListener(
            ISelectionChangedListener listener) {
         listeners.remove(listener);
      }

      public ISelection getSelection() {
         ISelection selection = new StructuredSelection(monitor);
         return selection;
      }

      public void setSelection(ISelection selection) {
         if (selection instanceof IStructuredSelection) {
            IStructuredSelection structuredSelection = (IStructuredSelection) selection;
            if (structuredSelection.size() == 1) {
               Object object = structuredSelection.getFirstElement();
               if (object instanceof Monitor) {
                  monitor = (Monitor) object;
               }
            }
         }
      }
   }
}
